package com.ztf0337.mycurriculumdesign.adapter;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.ztf0337.mycurriculumdesign.R;
import com.ztf0337.mycurriculumdesign.Utils.CompareClassUtil;
import com.ztf0337.mycurriculumdesign.entity.ParkLot;
import java.util.List;

public class ParkLotAdapter extends RecyclerView.Adapter<ParkLotAdapter.ViewHolder> {

    private List<ParkLot> parkLotList;
    private OnItemClickListener listener;  // 监听器引用

    public ParkLotAdapter(List<ParkLot> parkLotList) {
        this.parkLotList = parkLotList;
    }

    // 定义点击事件接口
    public interface OnItemClickListener {
        void onItemClick(ParkLot parkLot);
    }

    // 提供设置监听器的方法
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    @NonNull
    @Override
    public ParkLotAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_park_lot, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ParkLotAdapter.ViewHolder holder, int position) {
        ParkLot parkLot = parkLotList.get(position);
        holder.nameTextView.setText(parkLot.getParkLotName());
        // 给每个item绑定点击事件，调用回调接口
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(parkLot);
            }
        });
    }

    @Override
    public int getItemCount() {
        return parkLotList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView nameTextView;
        public ViewHolder(View view) {
            super(view);
            nameTextView = view.findViewById(R.id.parking_lot_name);
        }
    }

    // 更新整个数据集
    @SuppressLint("NotifyDataSetChanged")
    public void updateData(List<ParkLot> newData) {
        this.parkLotList = newData;
        notifyDataSetChanged();  // 简单刷新全部（低效）
    }

    // 只新增一项
    public void addItem(ParkLot newItem) {
        parkLotList.add(newItem);
        notifyItemInserted(parkLotList.size() - 1);
    }

    // 修改一项
    public void updateItem(ParkLot newItem) {
        parkLotList.set(CompareClassUtil.compareParkLot(parkLotList,newItem), newItem);
        notifyItemChanged(CompareClassUtil.compareParkLot(parkLotList,newItem));
    }

    // 删除一项
    public void removeItem(ParkLot newItem) {
        int index = CompareClassUtil.compareParkLot(parkLotList, newItem);
        if (index != -1) {
            parkLotList.remove(index);
            notifyItemRemoved(index);
        }
    }

}
